package com.tourism.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tourism.entity.ScenicRating;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface ScenicRatingMapper extends BaseMapper<ScenicRating> {

    // 分页查询评分列表
    @Select({
            "<script>",
            "SELECT r.*, u.username as user_name, s.name as spot_name",
            "FROM scenic_rating r",
            "LEFT JOIN user u ON r.user_id = u.id",
            "LEFT JOIN scenic_spot s ON r.spot_id = s.id",
            "WHERE 1=1",
            "<if test='spotId != null'>",
            "  AND r.spot_id = #{spotId}",
            "</if>",
            "<if test='userName != null and userName != \"\"'>",
            "  AND u.username LIKE CONCAT('%', #{userName}, '%')",
            "</if>",
            "ORDER BY r.rating_time DESC",
            "</script>"
    })
    IPage<ScenicRating> selectRatingPage(Page<ScenicRating> page,
                                         @Param("spotId") Integer spotId,
                                         @Param("userName") String userName);

    // 计算景点平均评分
    @Select("SELECT ROUND(AVG(rating), 1) FROM scenic_rating WHERE spot_id = #{spotId}")
    Double selectAvgRating(@Param("spotId") Integer spotId);

    // 获取景点评分数量
    @Select("SELECT COUNT(*) FROM scenic_rating WHERE spot_id = #{spotId}")
    Integer selectRatingCount(@Param("spotId") Integer spotId);

    // 获取用户评分数量
    @Select("SELECT COUNT(*) FROM scenic_rating WHERE user_id = #{userId}")
    Integer selectUserRatingCount(@Param("userId") Integer userId);
}